import os

import requests
import json
import configparser
import logging
import logging.handlers
import sys
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QMessageBox, QApplication, QLabel

# 获取token
def token():
    url = f"https://10.93.48.10/oapi/v1/token?accessKey=47893a23-e8e2-4ce0-a81a-5cf9a3ea8620&secretKey=7a3fa655-dd4d-416b-81e0-99f71a4e5620"
    print(url)

    headers = {
        "Content-Type":"application/json"
    }

    res = requests.get(url=url,headers=headers,verify=False)
    print(res.text)
    print(json.loads(res.text)["result"]["access_token"])
    return json.loads(res.text)["result"]["access_token"]


# 上传文件
def uploadfile(file_path):
    """
    procCode: 上传文件路径
    """
    queue_url = 'https://10.93.48.10' + '/oapi/v1/share/file'

    header = {
        'accesstoken': token(),
    }
    data = {
        "isOverwrite":"yes", # 是否覆盖写入
        "fileTag" : '', # 文件标注
        "userId" :  142,  # 用户ID
    }
    try:
        with open(file_path,'rb') as f:
            files={'uploadFile':f}
            req = requests.post(queue_url,data=data,files=files,verify=False, headers=header, timeout=5)
    except Exception:
        print('上传文件失败')
        sys.exit()
        

# 任务调度        
def job_run():
    # 任务ID
    id = 160
    url = 'https://10.93.48.10/oapi/v1/job/create?id=' + str(id)
    
    header = {
        "accesstoken":token(),
        "Content-Type":"application/json"
    }

    print("请求前")
    res = requests.post(url=url,headers=header,verify=False)
    print("请求后")
    print(res.text)

def run():
    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "config.ini"
    config = configparser.ConfigParser()
    config.read(config_file_path, encoding='utf-8')
    path = config.get("file_path", "path")
    # 任务调用
    uploadfile(path)
    job_run()
    return True

class win(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(180)
        self.setWindowTitle(" ")

        layout = QVBoxLayout()
        openConfig = QPushButton("打开配置", self)
        # openConfig.setText()
        # openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("RPA运行"))
        # layout.addWidget(QLabel("文件"))
        layout.addWidget(openConfig)
        # layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        # openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "config.ini"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def start(self):
        try:
            res = run()
        except Exception as e:
            print(repr(e))
            res = False

        if res:
            QMessageBox.information(self, "", "处理成功！")
        else:
            QMessageBox.critical(self, "", "处理失败，请查看后台日志！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())
    
